import React, { useEffect, useRef, useState } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { observer } from 'mobx-react-lite';
import { View, Text, Image, Button } from '@tarojs/components';

import './index.less';
import TitleBar from '@/src/components/titleBar';
import CommonPopup from '@/src/components/commonPopup';
import TitleBarLeft from '@/src/components/titleBarLeft';
import { getNetWorkStatus } from '@/src/common/util/util';
import store from '@/src/store';
import { netWorkErrorInfo } from '@/src/utils/constants';
import {
  oneClickLoginFun,
  updateInfoFun,
} from '@/src/common/method/userInfoFun';
import {
  oauthTokenFun,
  updateBasicInfoFun,
  userInfoFun,
} from '@/src/common/method/loginFun';
import {
  feature,
  getRandomCombination,
  identity,
  sence,
} from '@/src/utils/commonFun';
import LoadingSpinner from '@/src/components/loadingSpinner';

const LoginPage = () => {
  const [barHeight, setBarHeight] = useState(0);
  const [agreed, setAgreed] = useState<boolean>(false);
  const [showPopup, setShowPopup] = useState<boolean>(false);
  const [loadingText, setLoadingText] = useState<string>('');

  useDidShow(async (options: any) => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
    // 1. 获取临时登录凭证 code
    const loginRes: any = await Taro.login();
    if (!loginRes.code) {
      Taro.showToast({
        title: '登录失败',
        icon: 'success',
      });
      return;
    }
  });
  useEffect(() => {
    const sys: any = Taro.getSystemInfoSync();
    setBarHeight(sys.statusBarHeight); // 单位 px
  }, []);

  // 更新后台接口
  const updateInfo = (avatarUrl: any, nickname: any) => {
    const userId = Taro.getStorageSync('userId');
    updateInfoFun({
      ucUserId: userId,
      ucLoginPhone: Taro.getStorageSync('mobile'),
      ucNickname: nickname
        ? nickname
        : Taro.getStorageSync(`nickname-${userId}`),
      ucAvatarUrl: avatarUrl,
      address: store.commonStore.province,
    }).then((res: any) => {
      //更新一次后不再需要更新，退出后需要再次更新
      store.commonStore.setNeedUpdateInfo(false);
    });
  };

  //更新用户信息
  const updateUserInfo = (avatarUrl: any, nickname: any, userId: string) => {
    let randomVal: any = '';
    const nicknameStore = Taro.getStorageSync(`nickname-${userId}`);
    if (!nicknameStore && !nickname) {
      randomVal = getRandomCombination(feature, identity, sence, '');
      Taro.setStorageSync(`nickname-${userId}`, randomVal);
    }
    Taro.setStorageSync(`avatarUrl-${userId}`, avatarUrl);
    //1.更新U家nickname信息
    updateBasicInfoFun({
      access_token: store.commonStore.accessToken,
      userId: Taro.getStorageSync('userId'),
      nickname: nickname ? nickname : randomVal,
    })
      .then((res: any) => {
        //2.登录成功后，刷新后台用户信息
        updateInfo(avatarUrl, nickname ? nickname : randomVal);
      })
      .catch((e: any) => {
        updateInfo(avatarUrl, nickname ? nickname : randomVal);
      });
  };

  //查询个人信息
  const getUserInfo = () => {
    userInfoFun({
      access_token: store.commonStore.accessToken,
    })
      .then((res: any) => {
        //保存个人信息
        Taro.setStorageSync('mobile', res.mobile);
        Taro.setStorageSync('userId', res.userId);
        //用户昵称从[特征] + 人物身份/状态] + [氛围/动作/场景]随机组合，和重复
        //首页进入页面没有昵称的时候随机生成一个昵称
        console.log(res, 'res=========');
        updateUserInfo(res.avatarUrl, res.nickname, res.userId);
      })
      .catch((e: any) => {});
  };

  //手机号登录/注册方法
  const registerFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({ url: '/subPagesAuth/register/index' });
  };

  const handleGetPhoneNumber = async (e: any) => {
    // 1. 获取临时登录凭证 code
    const loginRes = await Taro.login();
    // 2.获取用户手机号
    // 在这里可以添加其他逻辑，如发送请求到服务器解密手机号
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      oneClickLoginFun({
        code: loginRes.code,
        phoneCode: e.detail.code,
      }).then((res: any) => {
        if (res.code === '0') {
          setLoadingText('正在登录...');
          oauthTokenFun({
            client_id: 'wpmkulfignec',
            client_secret: 'VrK2!cW1IDs3f_',
            grant_type: 'password',
            connection: 'type_wechat_access_token',
            username: res.data.purePhoneNumber,
            wechat_access_token: res.data.accessToken,
            wechat_openid: res.data.openid,
            wechat_scene: 0,
            wechat_client_ip: '10.191.136.112',
            wechat_appid: 'wx7042c1d52ab35d54',
          })
            .then((res: any) => {
              Taro.setStorageSync('access_token_login', res.access_token);
              Taro.setStorageSync('refresh_token_login', res.refresh_token);
              const loginOut = Taro.getStorageSync('loginOut');
              if (loginOut === '1') {
                //跳转到首页
                Taro.switchTab({ url: '/pages/home/index' });
                store.commonStore.setActiveTab(0);
                setTimeout(() => {
                  Taro.removeStorageSync('loginOut');
                }, 2000);
              } else {
                setTimeout(() => {
                  Taro.navigateBack();
                  setLoadingText('');
                }, 1000);
              }
              getUserInfo();
            })
            .catch((e: any) => {
              console.log(e, '一键登录失败了');
              setLoadingText('');
            });
        }
      });
    } else {
      // 用户拒绝授权
      console.log('用户拒绝授权获取手机号');
    }
  };

  const handleButtonClick = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!agreed) {
      setShowPopup(true);
      return false;
    }
  };

  //拒绝按钮
  const refuseFun = () => {
    setShowPopup(false);
  };

  //同意按钮
  const agreeFun = () => {
    setAgreed(true);
    setShowPopup(false);
  };

  const gotoPrivacyProtectFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({ url: '/subPagesAuth/privacyPolicy/index' });
  };

  //弹框内容
  const content = () => {
    return (
      <View className="privacy-protect-modal">
        <View className="privacy-protect-desc">
          在你使用服务之前，请仔细阅读
          <Text
            className="privacy-protect-guide"
            onClick={() => gotoPrivacyProtectFun()}
          >
            《酒联网小程序隐私保护指引》
          </Text>
          。当您点击同意并开始使用产品服务时，即表示你已理解并同意该条款内容，该条款将对您产生法律约束力。如您拒绝，将会限制一些功能的使用。
        </View>
        <View className="common-btn">
          <Button className="common-btn-refuse" onClick={() => refuseFun()}>
            拒绝
          </Button>
          <Button className="common-btn-agree" onClick={() => agreeFun()}>
            同意
          </Button>
        </View>
      </View>
    );
  };
  //点击同意复选框
  const handleAgree = () => {
    setAgreed(!agreed);
    Taro.setStorageSync('agreeProto', !agreed);
  };
  return (
    <View className="login-page custom-left">
      <View>
        <TitleBar
          customLeft={TitleBarLeft({ flag: true })}
          title="登录/注册"
        ></TitleBar>
        <View className="page-body">
          <View className="logo-wrap">
            <Image
              className="home-logo"
              src={'https://file.linkcook.cn/image/wineMiniProgram/logo.png'}
            />
          </View>

          <View className="btn-group">
            {/* 自定义按钮 - 用于前置校验 */}
            {agreed && (
              <Button
                className="login-btn-dark"
                open-type="getPhoneNumber"
                onGetPhoneNumber={handleGetPhoneNumber}
                onClick={handleButtonClick}
              >
                用户一键登录
              </Button>
            )}
            {!agreed && (
              <Button className="login-btn-dark" onClick={handleButtonClick}>
                用户一键登录
              </Button>
            )}

            <Button
              className="login-btn-light"
              style={{ marginTop: '20px' }}
              onClick={() => registerFun()}
            >
              手机号登录/注册
            </Button>
          </View>

          <View className="checkbox-wrap">
            <Image
              src={
                agreed
                  ? 'https://file.linkcook.cn/image/wineMiniProgram/login/checked.png'
                  : 'https://file.linkcook.cn/image/wineMiniProgram/login/unchecked.png'
              }
              onClick={() => {
                handleAgree();
              }}
              className="check-icon"
            />
            我已阅读并同意
            <text
              className="login-checkbox-link"
              onClick={() => {
                Taro.navigateTo({
                  url: '/subPagesAuth/userAgreement/index',
                });
              }}
            >
              《用户协议》
            </text>
            和
            <text
              className="login-checkbox-link"
              onClick={() =>
                Taro.navigateTo({ url: '/subPagesAuth/privacyPolicy/index' })
              }
            >
              《隐私政策》
            </text>
          </View>
        </View>
      </View>

      <CommonPopup
        visible={showPopup}
        onClose={() => {
          setShowPopup(false);
        }}
        className="loginPopupClass"
        full={false}
        title="用户隐私保护提示"
        closeBtn={false}
        content={content()}
      ></CommonPopup>
      <LoadingSpinner text={loadingText} />
    </View>
  );
};

export default observer(LoginPage);
